#!/usr/bin/env python
# -*- coding: utf-8 -*-
import inspect

from mako.template import Template as MakoTemplate
from mako.lookup import TemplateLookup
import os


#MYLOOKUP = TemplateLookup(directories=["common/","../../common/",".","../.."])
MYLOOKUP = TemplateLookup(directories=[os.path.dirname(__file__),os.getcwd()])

BTN = {}
for i in os.listdir("common/static"):
    if i.lower().endswith(".gif"):
        BTN[i[:-4]]=i

def Template(head,nom=None):
    global MYLOOKUP
    assert type(head)==dict
    #glob = inspect.currentframe(1).f_globals
    loc = inspect.currentframe(1).f_locals
    if "self" in loc:
        del(loc["self"])

    if nom:
        filename=nom
    else:
        filename = "templates/"+inspect.currentframe(1).f_code.co_name+".html"

    # meta par defaut
    head["home_page"]="/index"
    head["digit_key"]="false"
    
    loc["isFreeBox"] = Template.isFreeBox
    loc["rlinks"]=[]
    loc["headers"]=""
    for key,value in head.items():
        # mapping gestion feedbox -> telecommande
        if key=="BACK": key="star"
        if key=="NEXT": key="next"
        if key=="PREV": key="prev"
        if key=="PLAY": key="pause" # sur HD pas de touche play : uniquement play/pause
        if key=="PAUSE": key="pause"
        
        meta,rl=gen(key,value)
        loc["headers"]+=meta+"\n"
        loc["rlinks"].append(rl)

   
    mytemplate = MakoTemplate(filename=filename,output_encoding='iso-8859-15', encoding_errors='replace',lookup=MYLOOKUP)
    return mytemplate.render(**loc)

Template.isFreeBox=False    
    

def mkButton(key,value):
    global BTN
    if key in BTN:
        key = """<img src="%s">""" % BTN[key]
    return """<span onclick="document.location='%s';">%s</span>""" % (value,key)

def gen(key,value):
    key=key.lower()
    if type(value) in (str,unicode):
        assert '"' not in value
    button=""    
    if key in "help options red green yellow blue info guide stop play pause rec up down left right star sharp".split(" "):
        # balise LINK
        ret= """<link rel="%s" href="%s"> """ % (key,value)
        if value and value!="none":
            button=mkButton(key,value)
    elif key in "back prev next rev fwd pip".split(" "):
        # balise LINK (freebox HD ONLY !!!!)
        if value and value!="none":
            button=mkButton(key,value)
        ret= """<link rel="%s" href="%s"> """ % (key,value)
    elif key in "volume_key program_key wait_new_picture digit_key".split(" "):
        # balise FLAGS
        ret= """<flags %s="%s">""" % (key,value and "true" or "false")
    else:
        # balise META
        p=""
        
        # traitement vrai navigateur
        if key in "home_page love_page love2_page mail_page mail2_page nochannel_page channel_page star_page sharp_page settings_page".split(" "):
            # genere un vrai lien
            if value and value!="none":
                button=mkButton(key,value)
        elif key=="refresh":
            # genere un vrai refresh http pour un vrai navigateur
            p="""<META HTTP-EQUIV="Refresh" CONTENT="%s">""" % value
            
        ret= """<meta name="%s" content="%s">%s""" % (key,value,p)
        
    return ret,button

